var prefix = "/approval";
var pageInit = null;
var wrapper = new Vue({
    el : '#content',
    data : {
        total : 0,
        selectRowsTotal: 0,
        selectAppIds: [],
        title:'',
        creationDate:''
    },
    watch:{
        selectRowsTotal: function (newValue, oldValue) {
            if(newValue == 0){
                $("#selectCkDiv").hide();
                $("#notSelectCkDiv").show();
            }else{
                $("#notSelectCkDiv").hide();
                $("#selectCkDiv").show();
            }
        }
    }
})
$(function() {
    load();
    $(".fixed-table-pagination").remove();
	$(".fixed-table-loading").remove();
	$(".detail_btn").bind("click",detailBtn);
	$("#searchName").bind("keypress",searchEvent);
    $(".main_search span").bind("click",clickSearchEvent);
    $(".refresh_btn").bind("click",refreshEvent);

    $(".search").on("click","li",searchByOpt)

    pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;

    $("#searchName").bind('input propertychange', function(){
        wrapper.title=$('#searchName').val();
        wrapper.author=$('#searchName').val();

        if($('#searchName').val()==''){
            wrapper.creationDate='20180101';
        }else{
            wrapper.creationDate=$('#searchName').val();
        }
    })

    /*$("#centerDetail").scroll(function(){
        var nDivHight = $(this).height();
        var nScrollHight = $(this)[0].scrollHeight;
        var nScrollTop = $(this)[0].scrollTop;

        if(nScrollHight - (nScrollTop + nDivHight) < 1){
            loadMoreData();
		}
    });*/

    $("table").on("post-header.bs.table",function() {
        $('.fixed-table-body').on("scroll", function () {
            console.log($(this).scrollTop() + $(this).innerHeight() - $(this)[0].scrollHeight)
            if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight)
            {
              loadMoreData();
            }
          });
    });
});

function load() {
	$('#dataTable')
		.bootstrapTable(
			{
				method : 'get', // 服务器数据的请求方式 get or post
				url : prefix + '/query/listPostponed', // 服务器数据的加载地址
				cache: false,
				//	showRefresh : true,
				//	showToggle : true,
				//locale: "zh-CN",
				locale: "en-US",
				//locale: "ko-KR",
				iconSize : 'outline',
				toolbar : '#exampleToolbar',
				striped : false, // 设置为true会有隔行变色效果
				dataType : "json", // 服务器返回的数据类型
				pagination : true, // 设置为true会在底部显示分页条
				// queryParamsType : "limit",
				// //设置为limit则会发送符合RESTFull格式的参数
				singleSelect : false, // 设置为true将禁止多选
				// contentType : "application/x-www-form-urlencoded",
				// //发送到服务器的数据编码类型
				pageSize : 50, // 如果设置了分页，每页数据条数
				pageNumber : 1, // 如果设置了分页，首页页码
				//search : true, // 是否显示搜索框
				showColumns : false, // 是否显示内容下拉框（选择显示的列）
				sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
				queryParams : function(params) {
					return {
						//说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                        pageSize : params.limit,
						pageNum : params.pageNum,
                        title : $('#searchName').val(),
                        isDelete: 'N',
						orderBy:'create_time desc'
					};
				},
				onPostBody: function () {
					     //改变复选框样式
					     $("#dataTable").find("input:checkbox").each(function (i) {
					         var $check = $(this);
					         if ($check.attr("id") && $check.next("label")) {
					            return;
					         }
					         var name = $check.attr("name");
					         var id = name + "-" + i;
					         var $label = $('<label for="'+ id +'"></label>');
					         $check.attr("id", id).parent().addClass("bella-checkbox").append($label);
					    });
				},
				onClickRow: function(row, $element, field) {
					//$element.addClass("trCurrent");
				},
				onDblClickRow: function(row, $element, field) {
					maxView(row.appId,row.title)
				},
				onLoadSuccess:function(data){
					wrapper.total = data.total
				},
				onCheck:function(row){
					wrapper.selectRowsTotal ++;
					wrapper.selectAppIds.push(row.appTemplateId);
				},
				onUncheck:function(row){
					wrapper.selectRowsTotal --;
					removeUncheckedId(wrapper.selectAppIds,row.appTemplateId)
					//wrapper.selectAppIds.remove(row.appId);
				},
				onCheckAll:function(rows){
					wrapper.selectRowsTotal = rows.length;
					$.each(rows,function(index,row){
						wrapper.selectAppIds.push(row.appTemplateId);
					});
				},
				onUncheckAll:function(rows){
					wrapper.selectRowsTotal = 0;
					wrapper.selectAppIds.length = 0;
				},
				// //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
				// queryParamsType = 'limit' ,返回参数必须包含
				// limit, offset, search, sort, order 否则, 需要包含:
				// pageSize, pageNumber, searchText, sortName,
				// sortOrder.
				// 返回false将会终止请求
				columns : [
					{
						checkbox : true,
						class:'bella-checkbox',
						width:'30px'
					},
					{
						field : 'appTemplateId',
						title : 'ID',
						visible: false
					},
					{
						field : 'title',
						title : 'Title',
						width: '48%',
						formatter : function(value, row, index) {
							var e = '<a class="titleTable" href="#" title=\''+value+'\'  onclick="openEdit(\'' + row.appTemplateId + '\')">'+value+'</a> ';
							return e;
						}
					},
					{
						field : 'createUserNm',
						title : 'Author',
						width : '20%',
						formatter : function(value, row, index) {
							var e = '<a href="#" title=\''+value+'\'  onclick="showEmp(\'' + value + '\')">'+value+'</a> ';
							return e;
						}
					},
					{
						field : 'createTimeString',
						title : 'Create date',
						width : '15%'
					},
					{
						title : 'Type',
						width : '15%',
						formatter : function(value, row, index) {
							var e = "<span style='font-size:12px'>"+row.urgentTypeString+",Postponed</span>" ;
							return e;
						}
					} ]
			});
}

function loadMoreData() {
    $.ajax({
        url : $('#dataTable').bootstrapTable('getOptions').url,
        type : 'get',
		async:false,
		timeout:2000,
		data:{
            pageSize : 20,
            pageNum : pageInit,
            title : $('#searchName').val(),
            orderBy:'create_time desc'
		},
        success : function(data) {
			if(data.list!=undefined && data.list.length>0){
                pageInit++
                $('#dataTable').bootstrapTable('append', data.list);
			}
        }
    });
}

function detailBtn(){
	/*$('#dataTable').bootstrapTable({locale: "en-US"});*/
}

function searchByOpt(){
    var optTitle ='';
    var optCreationDate ='';

    switch ($(this).attr("value")) {
        case 'title':
            optTitle=$("#searchName").val().trim();
            break;
        case 'creationDate':
            optCreationDate=$("#searchName").val().trim();
            break;
    }
    var opt = {
        query: {
            title: optTitle,
            createTime:optCreationDate,
        }
    }
    if(optTitle !== ''|| optCreationDate !== ''){
        $('#dataTable').bootstrapTable('refresh', opt);
        pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
    }
}

function refreshEvent(){
    var opt = {
        query: {
            title: ''
        }
    }
    $('#dataTable').bootstrapTable('refresh',opt);
}

function showEmp(id){
	console.log(id);
}

function openEdit(appTemplateId) {
    var url = "/approval/view/showEditPostponed/"+appTemplateId; //转向网页的地址;
    var name = ""; //网页名称，可为空;
    var iWidth = "1008"; //弹出窗口的宽度;
    var iHeight = "670"; //弹出窗口的高度;
    //window.screen.height获得屏幕的高，window.screen.width获得屏幕的宽
    var iTop = (window.screen.height - 30 - iHeight) / 2; //获得窗口的垂直位置;
    var iLeft = (window.screen.width - 10 - iWidth) / 2; //获得窗口的水平位置;
    window.open(url, name, 'height=' + iHeight + ',,innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
}

function clickSearchEvent() {
	var opt = {
		query: {
			title: $("#searchName").val().trim()
		}
	}
	$('#dataTable').bootstrapTable('refresh', opt);
	pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
}

function searchEvent(event) {
	if(event.keyCode == "13"){
        var opt = {
            query : {
                title : $(this).val().trim()
            }
        }
        $('#dataTable').bootstrapTable('refresh', opt);
        pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
	}
}

function batchDelMail(){
    layer.confirm('Are you sure to delete the approvals ?', {
            shade: 0,
            closeBtn: 0,
            title:'Notification',
            btn: ['Yes','No'] //按钮
        }, function(index){
            $.ajax({
                url : prefix + "/batchDeletePostponed",
                type : "post",
                traditional: true,
                data:{
                    appTemplateIds: wrapper.selectAppIds
                },
                success : function(r) {
                    if(r.code==0){
                        asyncRefreshPage()
                        wrapper.selectAppIds.length = 0
                        wrapper.selectRowsTotal = 0;
                        layer.close(index);
                        layer.msg("Delete successfully.");
                    }else{
                        layer.msg(r.msg);
                        return;
                    }
                }
            });
        }, function(){

        });
}

function asyncRefreshPage() {
    $('#dataTable').bootstrapTable('refresh');
    pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
}
